package data

import (
	"amount1/internal/biz"
	"context"
	"fmt"
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/trace"
	"gorm.io/gorm"
	"time"
)

// 不在事务中执行，初始化自己的db
func (a *amount1Repo) EditOrderMain(ctx context.Context, id uint32, changeValue int64) error {
	ctx, span := otel.Tracer("Data").Start(ctx, "EditOrderMain", trace.WithSpanKind(trace.SpanKindInternal))
	defer span.End()

	db := a.data.Mysql.Table(biz.OrderMainTableName).WithContext(ctx)

	// stock = stock + changeValue Notice 并发安全的修改方式
	err := db.Where("id = ?", id).UpdateColumn("stock", gorm.Expr("stock + ?", changeValue)).Error

	return err
}

// 在事务中执行，这里的db其实是ctx中携带的tx（在InTx方法中加进去的）
func (a *amount1Repo) EditOrderMainWithTX(ctx context.Context, id uint32, changeValue int64) error {
	ctx, span := otel.Tracer("Data").Start(ctx, "EditOrderMainWithTX", trace.WithSpanKind(trace.SpanKindInternal))
	defer span.End()

	// 注意需要指定表名
	db := a.data.DB(ctx).Table(biz.OrderMainTableName)

	// stock = stock + changeValue Notice 并发安全的修改方式
	err1 := db.Where("id = ?", id).UpdateColumn("stock", gorm.Expr("stock + ?", changeValue)).Error
	if err1 != nil {
		return err1
	}

	return nil
}

func (a *amount1Repo) CurrentRedisOption(ctx context.Context) error {
	ctx, span := otel.Tracer("Data").Start(ctx, "currentRedisOption", trace.WithSpanKind(trace.SpanKindInternal))
	defer span.End()

	currSlice := []string{"a", "b", "c", "d", "e"}
	pipe := a.data.Redis.Pipeline()
	for _, item := range currSlice {
		//redisKey := item
		pipe.Set(ctx, item, item, time.Minute*10)
	}
	_, errPE := pipe.Exec(ctx)
	if errPE != nil {
		return errPE
	}

	return nil
}

func (a *amount1Repo) DelRedisKeyDemo(ctx context.Context) error {
	redisKey := "login:app_sign_in_count:20230318"
	// Notice 删除成功de是1，否则是0，key不存在的话不会报错
	de, errDel := a.data.Redis.Del(ctx, redisKey).Result()
	fmt.Println("de:>>>>>> ", de)

	return errDel
}
